<?php

class stYoutubeToolboxclass {

    public function __construct($config, $option) {
        $this->config = $config;
        add_include_path($config['pluginDir'] . 'libs/');
        require_once 'Zend/Loader.php'; // the Zend dir must be in your include_path
        Zend_Loader::loadClass('Zend_Gdata_YouTube');
        Zend_Loader::loadClass('Zend_Gdata_AuthSub');
        Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
        Zend_Loader::loadClass('Zend_Uri_Http');
        Zend_Loader::loadClass('Zend_Gdata_YouTube_VideoEntry');
        Zend_Loader::loadClass('Zend_Gdata_App_MediaFileSource');
        Zend_Loader::loadClass('Zend_Http_Client');
        Zend_Loader::loadClass('Zend_Http_Client_Adapter_Socket');

//        $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
//                        $username = $config['default_youtube_user_name'],
//                        $password = $config['default_youtube_password'],
//                        $service = 'youtube',
//                        $client = null,
//                        $source = 'facebookapp',
//                        $loginToken = null,
//                        $loginCaptcha = null,
//                        $config['default_youtube_authenticate_url']
//        );
//        $this->youtube = new Zend_Gdata_YouTube($httpClient, null, null, $config['default_youtube_app_key']);
//        $this->youtube->setMajorProtocolVersion(2);
        
    }

    public function loadmodel($modelName) {
        $className = $modelName . "_model";
        $fileName = $this->config ['pluginDir'] . "models/{$modelName}.php";
        require_once $fileName;
        $obj = new $className($this->config);
        return $obj;
    }

    public function syncVideo() {
        $youtubevideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $youtubeplaylist_model = $this->loadmodel("stYoutubeToolboxplaylist");
        $youtube_playlist_video_model = $this->loadmodel("stYoutubeToolbox_playlist_video");

        $videoUploads = $this->getUploadVideo();        
        if(count($videoUploads) > 0){
            foreach ($videoUploads as $videoUpload) {                
                $youtubevideo_model->savestYoutubeToolboxVideo($videoUpload);
            }
        }
        

        $videoFavorites = $this->getFavoriteVideo();
        if(count($videoFavorites) > 0){
            foreach ($videoFavorites as $videoFavorite) {                
                $youtubevideo_model->savestYoutubeToolboxVideo($videoFavorite, 1);
            }
        }
        

        $playlistListFeeds = $this->getPlaylistVideo();
        if(count($playlistListFeeds) > 0){
            foreach ($playlistListFeeds as $playlistListFeed) {
                $youtubeplaylist_model->savestYoutubeToolboxPlayList($playlistListFeed);
                $youtube_playlist_video_model->savestYoutubeToolboxPlaylistVideo($playlistListFeed, $this->youtube);
            }
        }
        
    }

    public function getUploadVideo( $users = '') {
        if(empty($users))
            $users = $this->getUser();
        $videos = array();
        $i = 0;
        foreach ($users as $user) {
            $user_name = basename($user->user_channel);
            $this->youtube = $this->youtubeClientLogin($user);
            $videos[$i]['video_entry'] = $this->youtube->getUserUploads($user_name);
            $videos[$i]['user_id'] = $user->id;
            $i++;
        }
        return $videos;
    }

    public function getFavoriteVideo( $users = '' ) {
        if(empty($users))
            $users = $this->getUser();
        $videos = array();
        $i = 0;
        foreach ($users as $user) {
            $user_name = basename($user->user_channel);
            $this->youtube = $this->youtubeClientLogin($user);
            $videos[$i]['video_entry'] = $this->youtube->getUserFavorites($user_name);
            $videos[$i]['user_id'] = $user->id;
            $i++;
        }
        
        return $videos;
    }

    public function getPlaylistVideo() {
        $users = $this->getUser();
        $playlists = array();
        $i = 0;
        foreach ($users as $user) {
            $user_name = basename($user->user_channel);
            $this->youtube = $this->youtubeClientLogin($user);            
            $playlists[$i]['playlist_entry'] = $this->youtube->getPlaylistListFeed($user_name);
            $playlists[$i]['user_id'] = $user->id;
            $i++;
        }
        return $playlists;
    }

//    public function getPlaylistVideoEntry() {
//        return $this->youtube->getPlaylistVideoFeedUrl($this->username);
//    }

    public function editVideo($video_id, $data, $playlists, $data_old) {
        //In this case $this->youtube is created with the user on functin getVideo
        $videoEntry = $this->getVideo($video_id);
        if ($videoEntry) {
//                $videoEntry = $this->youtube->getFullVideoEntry($video_id);
//                var_dump($data);
//                die;
            $putUrl = $videoEntry->getEditLink()->getHref();
            $videoEntry->setVideoTitle($data['title']);
            $videoEntry->setVideoDescription($data['description']);
            $videoEntry->setVideoTags($data['tag']);
            $videoEntry->setVideoCategory($data['category']);

            $this->youtube->updateEntry($videoEntry, $putUrl);
        }
        if ($data['favorite'] == 1) {
            $this->addFavorite($video_id);
        } else {
            $this->removeFavorite($video_id);
        }
        if (is_array($playlists)) {
            $all_playlist = array();
            foreach ($playlists as $playlist) {
                $all_playlist[] = $playlist->playlist_id;
            }
        }
        $this->updatePlaylists($video_id, $data, $all_playlist, $data_old);
    }

    public function updatePlaylists($video_id, $data, $all_playlist, $data_old) {
        //In this case $this->youtube is created with the user on functin editVideo
//        $playlistListFeed = $this->getPlaylistVideo();
        $youtubevideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $result = $youtubevideo_model->getUserId($video_id);
        $user_id = $result;
        $user = $this->getUser(" id={$user_id}");
        $user = $user[0];
        $user_name = basename($user->user_channel);
        $playlistListFeed = $this->youtube->getPlaylistListFeed($user_name);

        if (count($data['playlist']) > 0) {
            $playlist_insert = array_diff($data['playlist'], $data_old['playlist']);
            //var_dump($playlist_insert);
            foreach ($playlist_insert as $playlist) {
                foreach ($playlistListFeed as $playlistToAddTo) {
                    if ($playlistToAddTo->playlistId->text == $playlist) {
                        $postUrl = $playlistToAddTo->getPlaylistVideoFeedUrl();
                        // video entry to be added
                        $videoEntryToAdd = $this->youtube->getVideoEntry($video_id);

                        // create a new Zend_Gdata_PlaylistListEntry, passing in the underling DOMElement of the VideoEntry
                        $newPlaylistListEntry = $this->youtube->newPlaylistListEntry($videoEntryToAdd->getDOM());

                        // post
                        try {
                            $this->youtube->insertEntry($newPlaylistListEntry, $postUrl);
                        } catch (Zend_App_Exception $e) {
                            //echo $e->getMessage();
                        }
                    }
                }
            }

            $playlist_delete = array_diff($data_old['playlist'], $data['playlist']);
            //var_dump(count($data['playlist']));
            foreach ($playlist_delete as $playlist) {
                foreach ($playlistListFeed as $playlistToDelete) {
                    if ($playlistToDelete->playlistId->text == $playlist) {
                        $feedUrl = $playlistToDelete->getPlaylistVideoFeedUrl();
                        $playlistVideoFeed = $this->youtube->getPlaylistVideoFeed($feedUrl);
                        foreach ($playlistVideoFeed as $playlistVideoEntry) {

                            if ($playlistVideoEntry->getVideoId() == $video_id) {
                                $playlistVideoEntry->delete();
                                break;
                            }
                        }
                    }
                }
            }
        } else {
            $playlist_delete = $all_playlist;
            foreach ($playlist_delete as $playlist) {
                foreach ($playlistListFeed as $playlistToDelete) {
                    if ($playlistToDelete->playlistId->text == $playlist) {
                        $feedUrl = $playlistToDelete->getPlaylistVideoFeedUrl();
                        $playlistVideoFeed = $this->youtube->getPlaylistVideoFeed($feedUrl);
                        foreach ($playlistVideoFeed as $playlistVideoEntry) {

                            if ($playlistVideoEntry->getVideoId() == $video_id) {
                                $playlistVideoEntry->delete();
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    public function getVideo($video_id, $user_id = '') {
        if(empty($user_id)){
            $youtubevideo_model = $this->loadmodel("stYoutubeToolboxvideo");
            $result = $youtubevideo_model->getUserId($video_id);
            $user_id = $result;
        }
        $user = $this->getUser(" id={$user_id}");
        $this->youtube = $this->youtubeClientLogin($user[0]);
        try {
            $videoEntry = $this->youtube->getFullVideoEntry($video_id);
            return $videoEntry;
        } catch (Zend_Gdata_App_HttpException $e) {
            return false;
        }
    }

    public function deleteVideo($video_id) {
        //In this case $this->youtube is created with the user on functin getVideo
        $videoEntry = $this->getVideo($video_id);
        if ($videoEntry) {

            $videoEntryToDelete = $videoEntry;
            $this->youtube->delete($videoEntryToDelete);
        }
    }

    public function addFavorite($video_id) {
//        $newFavoriteVideoEntry = $this->youtube->getVideoEntry($video_id);
        $newFavoriteVideoEntry = $this->getVideo($video_id);
        $youtubevideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $result = $youtubevideo_model->getUserId($video_id);
        $user_id = $result;
        $user = $this->getUser(" id={$user_id}");
        $user = $user[0];
        $user_name = basename($user->user_channel);
//        $this->youtube = $this->youtubeClientLogin($user);
        
        $favoritesFeed = $this->youtube->getUserFavorites($user_name);
        $this->youtube->insertEntry($newFavoriteVideoEntry, $favoritesFeed->getSelfLink()->href);
    }

    public function removeFavorite($video_id) {
//        $favoritesFeeds = $this->getFavoriteVideo();
        $youtubevideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $result = $youtubevideo_model->getUserId($video_id);
        $user_id = $result;
        $user = $this->getUser(" id={$user_id}");
        $user = $user[0];
        $user_name = basename($user->user_channel);
        $favoritesFeed = $this->youtube->getUserFavorites($user_name);
        foreach ($favoritesFeed as $favoriteVideoEntry) {
            if ($favoriteVideoEntry->getVideoId() == $video_id) {
                $favoriteVideoEntry->delete();
                break;
            }
        }
        
    }

    public function uploadVideo($data, $file) {
        $user = $this->getUser("user_id={$data['user_id']}");
        $this->youtube = $this->youtubeClientLogin($user[0]);
        // create a new VideoEntry object
        $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

        // create a new Zend_Gdata_App_MediaFileSource object
        $filesource = $this->youtube->newMediaFileSource($file['tmp_name']);
        $filesource->setContentType($file['type']);
        // set slug header
        $filesource->setSlug($file['name']);

        // add the filesource to the video entry
        $myVideoEntry->setMediaSource($filesource);

        $myVideoEntry->setVideoTitle($data['title']);
        $myVideoEntry->setVideoDescription($data['description']);
        // The category must be a valid YouTube category!
        $myVideoEntry->setVideoCategory($data['category']);

        // Set keywords. Please note that this must be a comma-separated string
        // and that individual keywords cannot contain whitespace
        $myVideoEntry->SetVideoTags($data['tag']);

        // upload URI for the currently authenticated user
        $uploadUrl = 'http://uploads.gdata.youtube.com/feeds/api/users/default/uploads';

        // try to upload the video, catching a Zend_Gdata_App_HttpException,
        // if available, or just a regular Zend_Gdata_App_Exception otherwise
        try {
            return $newEntry = $this->youtube->insertEntry($myVideoEntry, $uploadUrl, 'Zend_Gdata_YouTube_VideoEntry');
        } catch (Zend_Gdata_App_HttpException $httpException) {
            return 'fail httpException';
        } catch (Zend_Gdata_App_Exception $e) {
            return $e->getMessage();
        }
    }

    public function getTokenUpload($data) {
        $user = $this->getUser(" id ={$data['user_id']}");
        $this->youtube = $this->youtubeClientLogin($user[0]);
        $myVideoEntry = new Zend_Gdata_YouTube_VideoEntry();

        $myVideoEntry->setVideoTitle($data['title']);
        $myVideoEntry->setVideoDescription($data['description']);
        // The category must be a valid YouTube category!
        $myVideoEntry->setVideoCategory($data['category']);

        // Set keywords. Please note that this must be a comma-separated string
        // and that individual keywords cannot contain whitespace
        $myVideoEntry->SetVideoTags($data['tag']);

        $tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
        return $tokenArray = $this->youtube->getFormUploadToken($myVideoEntry, $tokenHandlerUrl);
    }

    public function cronjobStatistic() {
        $stYoutubeToolboxstatistics_model = $this->loadmodel("stYoutubeToolboxstatistics");
        $day = date('j');
        $month = date('n');
        $year = date('Y');
        $isCronjob = $stYoutubeToolboxstatistics_model->checkIsCronjobYet($day, $month, $year);
        if(!$isCronjob){
            $videoUploads = $this->getUploadVideo();
            if(count($videoUploads) > 1){
                foreach ($videoUploads as $videoUpload) {
                    $stYoutubeToolboxstatistics_model->saveStstatistics($videoUpload);
                }
            }
            

            $videoFavorites = $this->getFavoriteVideo();
            if(count($videoFavorites) > 1){
                foreach ($videoFavorites as $videoFavorite) {
                    $stYoutubeToolboxstatistics_model->saveStstatistics($videoFavorite);
                }
            }
        }
    }

    public function getStatusUpload($videoId) {
        $videoEntry = $this->getVideo($videoId);

        $control = $videoEntry->getControl();
        if ($control instanceof Zend_Gdata_App_Extension_Control) {
            return false;            
        }
        return true;
    }

    public function cronjobGetComment() {
        $stYoutubeToolboxvideo_model = $this->loadmodel("stYoutubeToolboxvideo");
        $stYoutubeToolboxcomment_model = $this->loadmodel("stYoutubeToolboxcomment");
        $args = array();
        $args['custom_query'] = "SELECT video_id, user_id
        FROM $stYoutubeToolboxvideo_model->_tableName
        ORDER BY `user_id` ASC
        ";        
        $results = $stYoutubeToolboxvideo_model->getRecords($args);
        $user_id = 0;
        if (count($results) > 0) {
            foreach ($results as $result) {
//                if($result->user_id != $user_id){
//                    $user_id = $result->user_id;
//                    $user = $this->getUser("user_id={$user_id}");
//                    $this->youtube = $this->youtubeClientLogin($user[0]);
//                }
                $commentFeed = $this->youtube->getVideoCommentFeed($result->video_id);
                $stYoutubeToolboxcomment_model->savestYoutubeToolboxComment($commentFeed, $result->video_id, $result->user_id);
            }
        }
        die;
    }

    public function getUser($where = ''){
        $args = array();
        if(!empty($where))
            $args['where'] = $where;
        $youtubeUser_model = $this->loadmodel("stYoutubeToolboxuser");
        return $results = $youtubeUser_model->getRecords($args);
    }

    public function youtubeClientLogin($user = null){
        $config = $this->config;
        $httpClient = Zend_Gdata_ClientLogin::getHttpClient(
                        $username = $user->user_name,
                        $password = $user->user_password,
                        $service = 'youtube',
                        $client = null,
                        $source = 'facebookapp',
                        $loginToken = null,
                        $loginCaptcha = null,
                        $config['default_youtube_authenticate_url']
        );
        $youtube = new Zend_Gdata_YouTube($httpClient, null, null, $config['default_youtube_app_key']);
        $youtube->setMajorProtocolVersion(2);
        return $youtube;
    }
}

?>